package monsters;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import game.Room;

public abstract class Monster extends Thread {
   
   public static final int MAX_SLEEP = 4000;
   public int MAX_PEACEFUL;
   public int MAX_UNPEACEFUL;
   protected Room room;
   protected Random rnd;
   private Room entry;
   private boolean alive = true;
   
   public Monster(String name, Room room, int maxPeaceful, int maxUnpeaceful) {
      this.MAX_PEACEFUL = maxPeaceful;
      this.MAX_UNPEACEFUL = maxUnpeaceful;
      setName(name);
      rnd = new Random();
      System.out.println(name);
      entry = room;
      this.room = room;
   }

   @Override
   public void run() {
      if (!room.containsMonster(this))
         room.enter(this);
      while(alive) {
         Room goRoom = chooseRoom();
         room.leave(this);
         room = goRoom;
         room.enter(this);
         
         say("Sisenesin ruumi " + room.getName());
         if (room.isLighted()) {
            doLightRoomActivity();
         } else {
            doDarkRoomActivity();
         }
         
         try {
            sleep(rnd.nextInt(MAX_SLEEP) + 1000);
         } catch (InterruptedException e) {
            say("Magamist segati!");
            e.printStackTrace();
         }
      }
   }
   
   protected abstract void doLightRoomActivity();

   protected abstract void doDarkRoomActivity();
   
   public void say(String msg) {
      System.out.println(getName() + ": " + msg);
   }
   
   private Room chooseRoom() {
      List<Room> rooms = new ArrayList<Room>();
      if (room.getNorth() != null)rooms.add(room.getNorth());
      if (room.getEast() != null)rooms.add(room.getEast());
      if (room.getSouth() != null)rooms.add(room.getSouth());
      if (room.getWest() != null)rooms.add(room.getWest());
      
      return rooms.get(rnd.nextInt(rooms.size()));
   }
   
   protected void fight(Monster target) {
      Monster loser = null;
      Monster winner = null;
      if (rnd.nextBoolean()) {
         loser = target;
         winner = this;
      } else {
         loser = this;
         winner = target;
      }
      System.out.println(winner.getName() + " oli tugevam kui " + loser.getName());
      if (rnd.nextBoolean()) {
         loser.death();
      }
   }
   
   protected void death() {
      alive = false;
      setName(getName() + "0");
      room.leave(this);
      room = entry;
      room.enter(this);
      System.out.println("UUS TÜÜP " + getName());
      alive = true;
   }
   
}
